<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/6/20
 * Time: 下午6:47
 */

namespace app\mall\logic;


use extend\Functions;
use extend\STATUS_CODE;

class Address
{
    /**
     * @purpose 创建收货地址
     * @param array $data
     * @param int $uid
     * @return array
     */
    public static function create (array $data, int $uid): array
    {
        if (!$data['name']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少姓名！'
            );
        }
        if (!$data['mobile']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少手机号码!'
            );
        }
        if (!Functions::check_phone_number($data['mobile'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '手机号码格式错误!'
            );
        }
        if (empty($data['province']) || empty($data['city']) || empty($data['county'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少区域信息!'
            );
        }
        if (!$data['detail']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少详细地址!'
            );
        }
        $data['uid'] = $uid;
        $model = new \app\model\Address();
        if ((int) $data['is_default'] === 2) {
            $model
                ->isUpdate(true)
                ->save(['is_default' => 1], ['uid' => $uid]);
        }
        $result = $model
            ->isUpdate(false)
            ->save($data);
        if ($result) {
            self::checkDefault($uid);
            return Functions::result(
                STATUS_CODE::SUCCESS,
                '添加成功'
            );
        }
        return Functions::result(
            STATUS_CODE::CREATE_FAIL,
            '创建失败'
        );
    }

    /**
     * @purpose 更新收货地址
     * @param array $data 必须包含id字段
     * @return array
     */
    public static function update (array $data, int $uid):array
    {
        if (!$data['id']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误！'
            );
        }
        if (!$data['name']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少姓名！'
            );
        }
        if (!$data['mobile']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少手机号码!'
            );
        }
        if (!Functions::check_phone_number($data['mobile'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '手机号码格式错误!'
            );
        }
        if (empty($data['province']) || empty($data['city']) || empty($data['county'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少区域信息!'
            );
        }
        if (!$data['detail']) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少详细地址!'
            );
        }
        $model  = new \app\model\Address();
        if ((int) $data['is_default'] === 2) {
            $model->save(['is_default' => 1], ['uid' => $uid]);
        }
        $result = $model
            ->save($data, ['id' => $data['id']]);
        if ($result) {
            self::checkDefault($uid);
            return Functions::result(
                STATUS_CODE::SUCCESS,
                '更新成功!'
            );
        }
        return Functions::result(
            STATUS_CODE::CREATE_FAIL,
            '更新失败'
        );
    }

    /**
     * @purpose 通过ID获取信息
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function info (int $id, int $uid):array
    {
        $model      = new \app\model\Address();
        $fields     = 'id,name,mobile,province,city,county,detail,town,is_default';
        $where['uid'] = $uid;
        if ($id) {
            $where['id'] = $id;
        } else {
            $where['is_default'] = 2;
        }
        $result     = $model
            ->where($where)
            ->field($fields)
            ->find();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }

    /**
     * @purpose 通过uid获取列表
     * @param int $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function items (int $uid):array
    {
        $model      = new \app\model\Address();
        $fields     = 'id,name,mobile,province,city,county,detail,town,is_default';
        $result     = $model
            ->where('uid', $uid)
            ->field($fields)
            ->order('is_default desc,create_at desc')
            ->select();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }

    /**
     * @purpose 删除收货地址, 支持批量删除
     * @param array $ids
     * @return array
     */
    public static function delete (array $ids, int $uid) :array {
        $result = \app\model\Address::destroy($ids);
        self::checkDefault($uid);
        if ($result) {
            return Functions::result(
                STATUS_CODE::SUCCESS,
                '删除成功'
            );
        }
        return Functions::result(
            STATUS_CODE::DELETE_FAIL,
            '删除失败'
        );
    }

    /**
     * @purpose 设置默认
     * @param int $id
     * @param int $uid
     * @return array
     * @throws \think\exception\PDOException
     */
    public static function setDefault(int $id, int $uid):array
    {
        $model = new \app\model\Address();
        $model->startTrans();
        $clear = $model
            ->save(['is_default' => 1], ['uid' => $uid]);
        $set   = $model
            ->save(['is_default' => 2], ['id' => $id]);
        if ($clear && $set) {
            $model->commit();
            return Functions::result(
                STATUS_CODE::SUCCESS,
                '设置成功'
            );
        }
        $model->rollback();
        return Functions::result(
            STATUS_CODE::UPDATE_FAIL,
            '设置失败!'
        );
    }

    /**
     * 检测是否有默认地址,如果没有则自动添加
     */
    private static function checkDefault ($uid)
    {
        $model = new \app\model\Address();
        $is_default = $model->total(['is_default' => 2, 'uid' => $uid]);
        $total = $model->total(['uid' => $uid]);
        if ($is_default < 1 && $total > 0) {
            $min = $model->where('uid', $uid)->min('id');
            $model->isUpdate(true)->save(['is_default' => 2], ['id' => $min]);
        }
    }
}